import { inExpression, likeExpression } from '@/utils/definitionExpressionHelper.js';
import { Switch, Checkbox } from 'antd';
import styles from './index.less';
import React, { useEffect, useState, useRef, useCallback } from 'react';
import { layerUtils, viewUtils } from '@/utils/arcgis';
import { useSelector, useDispatch } from 'umi';
import kls from 'classnames';
import { WORKING_TAB } from '@/models/app';
import { ELEMENT_RENDERLAYER_ID } from '../elementRender/index';
import { MODEL_LAYERID } from '../citySketch';

import { xor as _xor } from 'lodash';

const DONT_RENDER_LAYER_LIST = ['南部通道宜马三场', '宜马项目三场临建', '高浪路道路模型'];

const RENDER_CFG_LIST = [
  {
    value: 'notStartList',
    color: '#F2F4F7',
    color2: [242, 244, 247, 0.5],
    label: '未开始',
  },

  {
    value: 'doingList',
    color: '#A5FB3F',
    color2: [165, 251, 63, 0.5],
    label: '施工中',
  },
  {
    value: 'notCalculateList',
    color: '#3DFBFF',
    color2: [61, 251, 255, 1],
    label: '已完成',
  },
  {
    value: 'calculatedList',
    color: '#FDCE38',
    label: '已计量',
    color2: [253, 206, 56, 1],
  },
];

const PLAN_RENDER_CFG_LIST = [
  {
    value: 'planNotStartList',
    color: '#F2F4F7',
    color2: [242, 244, 247, 0.5],
    label: '计划未开始',
  },

  {
    value: 'planDoingList',
    color: '#A5FB3F',
    color2: [165, 251, 63, 0.5],
    label: '计划进行中',
  },
  {
    value: 'planFinishedList',
    color: '#3DFBFF',
    color2: [61, 251, 255, 1],
    label: '计划完成',
  },
];

function BuilidngFilter() {
  const [curRenderCfgList, setCurRenderCfgList] = useState(RENDER_CFG_LIST);
  const [renderCgfList, setRenderCgfList] = useState(RENDER_CFG_LIST.map(e => e.value));
  const [uniqueRenderCgfList, setUniqueRenderCgfList] = useState([]);
  const preExpress = useRef('');
  const dispatch = useDispatch();
  const addedBimNameList = useSelector(s => s.bimmodel.addedBimNameList);
  const allWbs = useSelector(s => s.projectPage.allWbs);
  const bimList = useSelector(s => s.bimmodel.bimList);
  const curWorkingTab = useSelector(s => s.app.curWorkingTab);
  const isInitRendered = useSelector(s => s.kanban.isInitRendered);


  const [tabHistory, setTabHistory] = useState(['home']);
  const [isShowElementRenderLyr, setIsShowElementRenderLyr] = useState(false);

  useEffect(() => {
    setTabHistory(e => [...e, curWorkingTab]);
    if (WORKING_TAB[4] === curWorkingTab) {
      setIsShowElementRenderLyr(true);
    }
  }, [curWorkingTab]);

  // 修显示和隐藏
  useEffect(() => {
    if (!allWbs || !isInitRendered) {
      return;
    }
    console.log(renderCgfList);
    setDefinitionExpression();
  }, [renderCgfList, allWbs, curRenderCfgList, isInitRendered]);

  // 模型颜色渲染
  useEffect(() => {
    if (!allWbs || !isInitRendered) {
      return;
    }
    console.log(uniqueRenderCgfList);
    // todo 先搞成定时吧
    // let timer = setInterval(() => {
    //   try {
    modelColorRender(allWbs, uniqueRenderCgfList);
    //   } catch (error) {}
    // }, 5000);
    // return () => {
    //   clearInterval(timer);
    // };
  }, [uniqueRenderCgfList, allWbs, isInitRendered, curRenderCfgList]);

  async function getAddedBimModelsLayers() {
    const view = await viewUtils.isViewReady();
    return addedBimNameList.reduce((r, layerName) => {
      const lyr = view.map.layers.find(l => l.title === layerName);
      if (lyr) r.push(lyr);
      return r;
    }, []);
  }

  async function setDefinitionExpression() {
    const view = await viewUtils.isViewReady();
    const roadModel = layerUtils.getLayerByTitle(view, '高浪路道路模型') || { visible: false };

    let _definitionExpression;
    if (renderCgfList.length === curRenderCfgList.length) {
      _definitionExpression = '';
    } else if (renderCgfList.length === 0) {
      _definitionExpression = inExpression('WBS编码', ['wbs占位']);
      roadModel.visible = false;
    } else {
      _definitionExpression = inExpression(
        'WBS编码',
        renderCgfList.reduce((r, e) => {
          console.log(allWbs[e]);
          r.push(...allWbs[e]);
          // r.push(...allWbs[e].slice(1000));
          return r;
        }, []),
      );
    }

    if (renderCgfList.indexOf('notStartList') !== -1) {
      roadModel.visible = true;
    } else {
      roadModel.visible = false;
    }

    // console.log(_definitionExpression);

    if (preExpress.current === _definitionExpression) {
      return;
    }

    const layers = await getAddedBimModelsLayers();
    layers.forEach(lyr => {
      function hideBuildingComponent(subLayer) {
        // 过滤模型
        if (subLayer.type === 'building-component') {
          subLayer.definitionExpression = _definitionExpression;
        }
      }
      lyr.allSublayers.forEach(hideBuildingComponent);
    });
    preExpress.current = _definitionExpression;
  }

  async function toggleCityModelingVisible(checked) {
    const view = await viewUtils.isViewReady();
    const eleLyr = view.map.findLayerById(ELEMENT_RENDERLAYER_ID);
    const modelLyr = view.map.findLayerById(MODEL_LAYERID);
    setIsShowElementRenderLyr(checked);
    if (eleLyr) {
      eleLyr.visible = checked;
    }
    if (modelLyr) {
      modelLyr.visible = checked;
    }
    if (window.flowRenderLayer) {
      window.flowRenderLayer.setVisible(checked);
    }
  }

  /**
   * 模型进度颜色渲染
   */
  async function modelColorRender(allWbs, uniqueRenderCgfList) {
    console.time('sublayers-unique-value');
    const _uniqValueRender = []; // todo 用于重置render
    curRenderCfgList
      .filter(e => {
        return uniqueRenderCgfList.some(value => {
          return value === e.value;
        });
      })
      .forEach(({ value, color2 }) => {
        allWbs[value].forEach(wbs => {
          _uniqValueRender.push({
            value: `${wbs}`,
            symbol: {
              type: 'mesh-3d',
              symbolLayers: [
                {
                  type: 'fill',
                  material: {
                    color: color2,
                    colorMixMode: 'replace',
                  },
                },
              ],
            },
          });
        });
      });

    const lyrs = await getAddedBimModelsLayers();
    lyrs.forEach(lyr => {
      // 不渲染的例外
      if (DONT_RENDER_LAYER_LIST.indexOf(lyr.title) !== -1) return;
      lyr.allSublayers.forEach(subLayer => {
        if (subLayer.type === 'building-component') {
          subLayer.renderer = {
            type: 'unique-value',
            field: 'WBS编码',
            uniqueValueInfos: _uniqValueRender,
          };
        }
      });
    });
    console.timeEnd('sublayers-unique-value');
  }

  async function toggleRoadLayer(isShow) {
    for (const item of bimList) {
      if (/道路/.test(item.name)) {
        await new Promise(res => {
          setTimeout(() => {
            dispatch({
              type: 'bimmodel/toggleBimLayer',
              payload: {
                id: item.bimId,
                active: isShow,
              },
            });
            res(true);
          }, 1000);
        });
      }
    }
  }

  /**
   * 触发唯一值渲染
   * @param {*} value
   */
  function handleUniqueRenderClick(value) {
    console.log(value, uniqueRenderCgfList);
    setUniqueRenderCgfList(pre => {
      return _xor(pre, [value]);
    });
  }

  return (
    <ul className={kls(styles.builidngFilter, { [styles.builidngFilterLeft2]: 1 })}>
      <li>
        {curRenderCfgList.length === 3 ? '计划状态' : '实际状态'}
        <Switch
          style={{ float: 'right' }}
          size="small"
          onChange={e => {
            setCurRenderCfgList(!e ? RENDER_CFG_LIST : PLAN_RENDER_CFG_LIST);
            setRenderCgfList((!e ? RENDER_CFG_LIST : PLAN_RENDER_CFG_LIST).map(e => e.value));
          }}
        />
      </li>

      {curWorkingTab !== WORKING_TAB[1] &&
        curRenderCfgList.map(({ label, color, value }, i) => {
          return (
            <li key={label}>
              <span
                onClick={() => handleUniqueRenderClick(value)}
                className={kls(styles.color, {
                  [styles.colorActive]: uniqueRenderCgfList.indexOf(value) >= 0,
                })}
                style={{
                  background: color,
                }}
              ></span>{' '}
              {label}{' '}
              <Checkbox
                style={{ float: 'right' }}
                checked={renderCgfList.indexOf(value) !== -1}
                onChange={() => {
                  setRenderCgfList(pre => {
                    return _xor(pre, [value]);
                  });
                }}
              />
            </li>
          );
        })}

      <div className={styles.line} />

      <li className={styles.control}>
        <div>道路模型</div>
        <div>
          <Switch size="small" disabled={!bimList.length} onChange={toggleRoadLayer} />
        </div>
      </li>
      <li className={styles.control}>
        <div>红线范围</div>
        <div>
          <Switch size="small" defaultChecked={false} />
        </div>
      </li>
      <li className={styles.control}>
        <div>临建设计</div>
        <div>
          <Switch
            size="small"
            checked={isShowElementRenderLyr}
            onChange={check => {
              toggleCityModelingVisible(check);
            }}
            disabled={tabHistory.indexOf(WORKING_TAB[4]) === -1}
          />
        </div>
      </li>
    </ul>
  );
}

export default BuilidngFilter;
